package com.zeltov.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.zeltov.bo.Car;
import com.zeltov.eo.CarEO;

@Repository("carDao")
public class CarDaoJPA extends AbstractGenericJpaDAO implements CarDAO {
 
	static Log log = LogFactory.getLog(CarDaoJPA.class);

    /* (non-Javadoc)
	 * @see com.zeltov.dao.CarDAO#persistCarEO(com.zeltov.bo.Car)
	 */
    @Override
	public void persistCarEO(Car car) {
        EntityManager em = createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
 
        em.persist(car);
 
        tx.commit();
        em.close();
    }
 
    /* (non-Javadoc)
	 * @see com.zeltov.dao.CarDAO#getAllCars()
	 */
    @Override
	@SuppressWarnings("unchecked")
    public List<Car> getAllCars() {
    	
    	log.debug("--############------getAllCarsEO------------------");
        EntityManager em = createEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();
 
        Query allCarEOsQuery = em.createQuery("select d from CarEO d");
 
        List<Car> allCarEOs = allCarEOsQuery.getResultList();
 
        tx.commit();
        em.close();
 
        return allCarEOs;
    }
    public static void main(String[] args) {
    	CarDAO dogDao = new CarDaoJPA();
    	 
        Car michalsCarEO = new CarEO();
        michalsCarEO.setName("Subaru");
        
        Car someOtherCarEO = new CarEO();
        someOtherCarEO.setName("Assan");
 
        try {
            dogDao.persistCarEO(michalsCarEO);
        } catch (Exception e) {
            System.err.println("Exception while saving dog: " + michalsCarEO);
            System.err.println(e);
            e.printStackTrace();
        }
 
        try {
            dogDao.persistCarEO(someOtherCarEO);
        } catch (Exception e) {
            System.err.println("Exception while saving dog: " + someOtherCarEO);
            System.err.println(e);
            e.printStackTrace();
        }
 
        List<Car> allCarEOs = dogDao.getAllCars();
        for (Car doggie : allCarEOs) {
            System.out.println(doggie);
        }
        AbstractGenericJpaDAO.closeEntityManager();
	}

}
